import myalert from '../../utils/alert';
import {init} from '../../utils/realtime';
export async function register({phone, msgcode}) {
  myalert.loading ();
  return await AV.User
    .signUpOrlogInWithMobilePhone (phone, msgcode)
    .then (user => {
      myalert.clear ();
      return user;
    })
    .catch (e => {
      myalert.clear ();
      myalert.fail (e.message);
      return e;
    });
}
export async function sendCode (phone) {
  myalert.loading ();
  return AV.Cloud
    .requestSmsCode (phone)
    .then (res => {
      myalert.clear ();
      myalert.success ('发送验证码成功，请查收');
    })
    .catch (e => {
      myalert.clear ();
      myalert.fail (e.message);
    });
}

function event_add_friend (message, conversation) {
  var _message = JSON.parse (message.text);
  if (_message.type == 'add_friend') {
    console.log ('有人请求添加信息', _message);
    var addFrends = this.$store.state.app.addFrends;
    addFrends.push (_message.payload.from);
    this.$store.commit ('app/snapShot', {addFrends});
  }
  // console.log ('Message received: ', );
}
function event_un_read (conversations) {
  var self = this;
  for (let conv of conversations) {
    if (conv.name == 'add friend') {
      // self.$store.commit ('app/snapShot', {});
    }
    console.log (conv, conv.id, conv.name, conv.unreadMessagesCount);
  }
}
export async function initEvent () {
  var self = this;
  var user = AV.User.current ();
  var realtime = init ();
  return realtime
    .createIMClient (user.toJSON ().objectId)
    .then (function (jerry) {
      jerry.off (AV.Event.MESSAGE, event_add_friend, self);
      jerry.on (AV.Event.MESSAGE, event_add_friend, self);
      jerry.off (AV.Event.UNREAD_MESSAGES_COUNT_UPDATE, event_un_read, self);
      jerry.on (AV.Event.UNREAD_MESSAGES_COUNT_UPDATE, event_un_read, self);
    })
    .catch (console.error);
}
